package com.mingqijia.gassafety.webserver.service.strategy;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.mingqijia.gassafety.db.entity.RunningStrategyExt;
import com.mingqijia.gassafety.db.mapper.WarningAlarmMapper;
import com.mingqijia.gassafety.shared.constant.CallTypeEnum;
import com.mingqijia.gassafety.shared.constant.Constants;
import com.mingqijia.gassafety.shared.utils.RedisCacheExt;
import com.mingqijia.gassafety.webserver.dto.CallTaskDTO;
import com.mingqijia.gassafety.webserver.service.AicallTaskService;
import com.mingqijia.gassafety.webserver.service.impl.EquipmentServiceImpl;
import com.mingqijia.gassafety.webserver.service.impl.WarningRecordServiceImpl;
import com.mingqijia.gassafety.webserver.service.impl.XFCallServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;

/**
 * @author zhangfei
 * @version 1.0.0
 * @ClassName CallTaskServiceImpl.java
 * @Description 呼叫任务
 * @createTime 2023年02月15日
 */
@Service
@Slf4j
public class CallTaskServiceStrategyImpl {

    @Autowired
    RedisCacheExt redisUtil;

    @Autowired
    XFCallServiceImpl xFCallService;
    @Autowired
    EquipmentServiceImpl equipmentService;
    @Autowired
    WarningAlarmMapper warningAlarmMapper;
    @Autowired
    WarningRecordServiceImpl recordService;
    @Autowired
    StrategyServiceImpl warnStrategyJob;
    @Autowired
    RunningStrategyServiceImpl runningStrategyJob;
    
    @Autowired
    AicallTaskService aicallTaskService;

    /**
     * 外呼
     * @param spId
     * @param phones
     * @param imei
     * @param type null   0设备故障 1设备离线 2设备运行报告
     * @param ext
     * @return
     */
    public Map<String, Object> sendCallTask(String spId, Set<String> phones, String imei,Integer type, RunningStrategyExt ext) {
        log.info("sendCallTask-外呼入参:spId:{},phones:{},imei:{}",
                spId, JSONObject.toJSONString(phones), imei);
        if (imei.contains("-")&&imei.split("-").length>=3){
            String[] split = imei.split("-");
            imei=split[0]+"-"+split[1]+"-"+split[2];
        }
        log.info("sendCallTask-imei:{}",imei);
        Map<String, Object> res = new HashMap<>();
        Map<String, Object> dtuInfos = equipmentService.selectByImei(imei, spId);
        Map<String, Object> paramMap = new HashMap<>();
        log.info("sendCallTask-selectByImei:{}", JSONObject.toJSONString(dtuInfos));
        CallTaskDTO callTaskDTO = new CallTaskDTO();
        List<JSONArray> calls = new ArrayList<>();
        if (dtuInfos == null) return null;
        String address = "";
        Object position = dtuInfos.get("installationPosition");
        if (Integer.parseInt(dtuInfos.get("templateType") + "") == 2) {
            address = dtuInfos.get("address") + "";
        } else {
            address = dtuInfos.get("custAddress") + "";
        }
        if (!StringUtils.isEmpty(address)) {

            address = "地址是在" + address;
            if (!StringUtils.isEmpty(position)) address = address + "(" + position + ")";
        }else {
            address="";
        }
        List<String> phoneList = new ArrayList<>();
        phones.forEach(s -> {
            phoneList.add(s);
        });
        Object name = dtuInfos.get("name");
        Object paramValue = dtuInfos.get("paramValue");
        Object factoryName = "";
        paramMap.put("name",name);
        paramMap.put("phone",paramValue);
        paramMap.put("address",address);
        paramMap.put("factoryName",factoryName);

        callTaskDTO = aicallTaskService.getAicallTaskByType(type, spId);
        boolean hasFactoryName = false;
        if ( null!=callTaskDTO.getRobotContent() && callTaskDTO.getRobotContent().contains("#factoryName#") ){
            factoryName = equipmentService.getEquipmentManufacturerName(
                    null==dtuInfos.get("equipmentManufacturer")?"":dtuInfos.get("equipmentManufacturer").toString(),
                    spId
            );
            paramMap.put("factoryName",factoryName);
            callTaskDTO.getCallColumn().add("厂家名称");
            hasFactoryName = true;
        }

        for (String phone : phoneList) {
            if (phone.contains("-"))phone = phone.replace("-", "");
            JSONArray array = new JSONArray();
           if (type==null)array.add(0, phone);
           if (type!=null&&(type==0||type==1))array.add(0, name);
            array.add(1, address);
            array.add(2, name);
            if (type==null||type!=2) array.add(3, paramValue);
            if (type!=null&&type==2) array.add(3, DateUtil.format(DateUtil.offsetMonth(new Date(), -1), "yyyy-MM"));
            if (type!=null)array.add(4, phone);
            if (hasFactoryName){
                array.add(array.size(), factoryName);
            }
            calls.add(array);
        }
        callTaskDTO.setCallList(calls);

        callTaskDTO = xFCallService.addCallExecTimeParam(callTaskDTO,ext);

        JSONObject jsonObject = null;
        try {
            jsonObject = xFCallService.callPoolCreate(callTaskDTO, spId);
        } catch (Exception e) {
            log.error("xFCallService-callCreate:{}",e);
            //res.put("errMsg",e.getMessage());
        }
        log.info("callTaskDetail-callCreate:{}", JSONObject.toJSONString(jsonObject));
        JSONArray data =null;
        if (jsonObject != null ){
             data = jsonObject.getJSONArray("call_ids");
            log.info("callTaskDetail-saveCallList:dtuInfos:{},data:{},spid:{}" +
                            "", JSONObject.toJSONString(dtuInfos)
                    , JSONObject.toJSONString(data), JSONObject.toJSONString(spId));
        }

        res.put("robotContent", callTaskDTO.getRobotContent());
        res.put("data", data);
        res.put("dtuInfos", dtuInfos);
        res.put("phoneList", phoneList);
        res.put("paramMap", paramMap);
        return res;
    }

    /**
     * 存储外呼记录
     *
     * @param data
     * @param phones
     * @return
     */
    public boolean saveCallList(JSONArray data, Map<String, Object> dtuInfos, Map<String, Object> paramMap,List<String> phones,
                                String spId, String iMEI,
                                Integer value, int report, String con, Object strategyId,
                                Integer level, Date date, int sendType, long snowflakeId, int sendResult,
                                String supIMEI,
                                String info, Map<String, Integer> objectTypeMap,Integer type,String robotContent,
                                String errMsg) {

        try {
            for (int i = 0; i < phones.size(); i++) {

                if (type==null){
                    String content = (StringUtils.isEmpty(robotContent)?Constants.WARNING_CALL_MESSAGES:robotContent)
                            .replace("#name#", paramMap.get("name") + "")
                            .replace("#address#", paramMap.get("address")+"")
                            .replace("#phone#", paramMap.get("phone")+"")
                            .replace("#factoryName#", paramMap.get("factoryName")+"");
                    warnStrategyJob.saveWarningRecord(spId, iMEI, value, report, con,
                            strategyId, level, date, sendType, snowflakeId, sendResult, content, supIMEI, errMsg,
                            data!=null?data.get(i) + "":"", phones.get(i) + "", objectTypeMap.get(phones.get(i)), info);
                }else {
                    String content ="";
                    if (type==0){
                         content = (StringUtils.isEmpty(robotContent)?Constants.WARNING_CALL_MESSAGES_OFFLINE:robotContent)
                                .replace("#name#", paramMap.get("name") + "")
                                .replace("#address#", paramMap.get("address")+"")
                                .replace("#phone#", paramMap.get("phone")+"")
                                 .replace("#factoryName#", paramMap.get("factoryName")+"");
                    }else if (type==1){
                        content = (StringUtils.isEmpty(robotContent)?Constants.WARNING_CALL_MESSAGES_BREAKDOWN:robotContent)
                                .replace("#name#", paramMap.get("name") + "")
                                .replace("#address#", paramMap.get("address")+"")
                                .replace("#phone#", paramMap.get("phone")+"")
                                .replace("#factoryName#", paramMap.get("factoryName")+"");
                    }else if (type==2){
                        content = (StringUtils.isEmpty(robotContent)?Constants.WARNING_CALL_MESSAGES_REPORT:robotContent)
                                .replace("#name#", paramMap.get("name") + "")
                                .replace("#address#", paramMap.get("address")+"")
                                .replace("#phone#", paramMap.get("phone")+"")
                                .replace("#date#", DateUtil.format(DateUtil.offsetMonth(new Date(), -1), "yyyy-MM"))
                                .replace("#factoryName#", paramMap.get("factoryName")+"");
                    }else if (type==3){
                        content = (StringUtils.isEmpty(robotContent)?Constants.WARNING_CALL_SERVICE_PERIOD:robotContent)
                                .replace("#name#", paramMap.get("name") + "")
                                .replace("#address#", paramMap.get("address")+"")
                                .replace("#phone#", paramMap.get("phone")+"")
                                .replace("#verb#", paramMap.get("verb")+"")
                                .replace("#date#", paramMap.get("date")+"")
                                .replace("#factoryName#", paramMap.get("factoryName")+"");
                    }

                    runningStrategyJob.saveWarningRecord(spId, iMEI, report, con,
                            strategyId, String.valueOf(level), date, sendType, snowflakeId, sendResult, content, supIMEI, errMsg,
                            data!=null?data.get(i) + "":"", phones.get(i) + "", 0, info);
                }
            }
        } catch (NumberFormatException e) {
            return false;
        }
        return true;
    }

    /**
     * 存储外呼记录
     *
     * @param data
     * @param phones
     * @return
     */
    public boolean saveCallInformList(JSONArray data, Map<String, Object> dtuInfos, Map<String, Object> paramMap,List<String> phones,
                                String spId, String iMEI,
                                Integer value, int report, String con, Object strategyId,
                                String level, Date date, int sendType, long snowflakeId, int sendResult,
                                String supIMEI,
                                String info, Map<String, Integer> objectTypeMap,Integer type,String robotContent,
                                String errMsg) {

        try {
            for (int i = 0; i < phones.size(); i++) {
                String content ="";
                if (type==0){
                    content = (StringUtils.isEmpty(robotContent)?Constants.WARNING_CALL_MESSAGES_OFFLINE:robotContent)
                            .replace("#name#", paramMap.get("name") + "")
                            .replace("#address#", paramMap.get("address")+"")
                            .replace("#phone#", paramMap.get("phone")+"")
                            .replace("#factoryName#", paramMap.get("factoryName")+"");
                }else if (type==1){
                    content = (StringUtils.isEmpty(robotContent)?Constants.WARNING_CALL_MESSAGES_BREAKDOWN:robotContent)
                            .replace("#name#", paramMap.get("name") + "")
                            .replace("#address#", paramMap.get("address")+"")
                            .replace("#phone#", paramMap.get("phone")+"")
                            .replace("#factoryName#", paramMap.get("factoryName")+"");
                }else if (type==2){
                    content = (StringUtils.isEmpty(robotContent)?Constants.WARNING_CALL_MESSAGES_REPORT:robotContent)
                            .replace("#name#", paramMap.get("name") + "")
                            .replace("#address#", paramMap.get("address")+"")
                            .replace("#phone#", paramMap.get("phone")+"")
                            .replace("#date#", DateUtil.format(DateUtil.offsetMonth(new Date(), -1), "yyyy-MM"))
                            .replace("#factoryName#", paramMap.get("factoryName")+"");
                }else if (type==3){
                    content = (StringUtils.isEmpty(robotContent)?Constants.WARNING_CALL_SERVICE_PERIOD:robotContent)
                            .replace("#name#", paramMap.get("name") + "")
                            .replace("#address#", paramMap.get("address")+"")
                            .replace("#phone#", paramMap.get("phone")+"")
                            .replace("#verb#", paramMap.get("verb")+"")
                            .replace("#date#", paramMap.get("date")+"")
                            .replace("#factoryName#", paramMap.get("factoryName")+"");
                }

                runningStrategyJob.saveWarningRecord(spId, iMEI, report, con,
                        strategyId, level, date, sendType, snowflakeId, sendResult, content, supIMEI, errMsg,
                        data!=null?data.get(i) + "":"", phones.get(i) + "", 0, info);
            }
        } catch (NumberFormatException e) {
            return false;
        }
        return true;
    }

}